package cn.com.controller.wxController;

import java.util.HashMap; 
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import cn.com.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;

import cn.com.Enum.SessionAttr;
import cn.com.constant.Code;
import cn.com.db.model.User;
import cn.com.db.service.UserService;
import cn.com.wxUtil.WXUtil;

/**
 * author: yue date: 2018/01/30 description:
 */
@RestController
@RequestMapping("/wx/")
public class WXInterfaceController {

	@Autowired
	UserService userService;

	@RequestMapping(value = "authorize/{code}", method = RequestMethod.GET)
	public String authorize(HttpServletRequest request, @PathVariable(value = "code") String code) {
		DataResult dataResult = new DataResult();
		JSONObject jsonObject = WXUtil.getUnionCode(code);
		if (jsonObject == null||jsonObject.get("openid")==null) {
			dataResult.setCode(Code.FORBIDDEN);
			dataResult.setMessage("获取用户授权失败");
			return JsonUtil.toJsonString(dataResult);
		}
//		String openId=jsonObject.getString("openid");
//		User user=userService.getUserByOpenId(openId);
//		if (user==null){
//			user=new User();
//			user.setId(UidUtil.createUUID());
//			user.setOpenId(openId);
//			user.setCreated_at(TimeUtil.getNowTimestamp());
//			user.setUpdated_at(TimeUtil.getNowTimestamp());
//			userService.createUser(user);
//		}
		Map map = new HashMap();
		map.put("openid", jsonObject.get("openid"));
		map.put("unionid", jsonObject.get("unionid"));
		dataResult.setData(map);
		dataResult.setCode(Code.SUCCESS);
		dataResult.setMessage("获取成功");
		return JsonUtil.toJsonString(dataResult);
	}

}
